<?php
/**
 * Baseclass for controller 
 */
class ClsNaanalController
{
    ///deprecated
    public $mode="create";
    protected $action=false;
    protected $id=null;
    protected $table="";
    protected $module="";
    protected $switch="";
    public $objParentModule=null;
    protected $arrConfigVar=array();
    protected $urlModuleParam="page";
    protected $urlActionParam="action";

    protected $database="";

    public $objPDO=null;
    public $controlpanel=null;
    protected $redirect=null; 
    public $wrapper=null;
    public $ui=null;
    public $isAddNew=true;

    private $arrField=array();

    public $itemperpage=20;
    public $arrOrderBy=array();

    //protected $isPartionExist=false;

    protected $fldID="id";
    
    protected $objNaanalRequest=null;
    protected $objNaanalPost=null;
    protected $objNaanalGet=null;
    
    protected $arrNaanalData=array();
    protected $arrAdditionalInput=array();
    
    protected $form=null;
    
    protected $arrWhere=array();
    ///global template variable holder
    private $arrTplVar=array();
    ///holder of html header datas
    private $arrHeaderData=array();
    ///sub template holder for processing in ClsNaanalModule
    private $arrSubTemplate=array();
    
    public static $arrErrorStatic=array();

    function __construct($module=false)
    {
        $this->urlModuleParam=ClsNaanalRequest::getInstance()->getUrlModuleParam();
        $this->urlActionParam=ClsNaanalRequest::getInstance()->getUrlActionParam();
        if($module!==false)
        {
            $this->module=$module;
        }
    }
    public function init()
    {
        $this->arrConfigVar=ClsNaanalApplication::getConfigVars($this->module);
        if($this->module=="install")
        {
            
        }
        else
        {
            $this->database=  getAppConfig("DATABASE_NAME");
            if(isset($this->arrConfigVar["database"]))
            {
                if($this->arrConfigVar["database"]!==true)
                {
                    $this->database=$this->arrConfigVar["database"];
                }
            }
            /*if(ClsNaanalApplication::$isClsConfigExist)
            {
                $this->database=$this->arrConfigVar["database"]===true?ClsNaanalApplication::getDefaultDatabase():$this->arrConfigVar["database"];
            }
            else
            {
                $this->database=$this->arrConfigVar["database"];
            }*/
            if($this->database)
            {
                $this->objPDO=ClsNaanalPDO::getNamedInstance($this->database,$this->database);
                $this->table=$this->arrConfigVar["table"];
            }
            $this->controlpanel=getCurrentControlPanel();
            $this->objNaanalRequest=ClsNaanalRequest::getInstance();
            $this->objNaanalPost=ClsNaanalPost::getInstance();
            $this->objNaanalGet=ClsNaanalGet::getInstance();
            $this->objNaanalSession=  ClsNaanalSession::getInstance();

            if(class_exists("ClsConfig") && isset(ClsConfig::$DATABASE) && !empty(ClsConfig::$DATABASE) && $this->table && !ClsNaanalApplication::$isDatabaseConnectivityError)
            {
                $this->form=  ClsWrapper::getInstance($this->module);
                if(!empty($this->id))
                {
                    $this->form->set_id($this->id);
                }
                $this->wrapper=  get_class($this->form);
                $this->arrField=getTableFields(ClsNaanalApplication::getCurrentDatabase(), $this->table);
            }
        }
    }
    public function get_fatal_error($code,$message)
    {
        $objModule=get_module_object("error", "fatal", 0, array("message"=>$message));
        $objModule->setSwitch($code);
        return $objModule->render();
    }
    public function setHeaderData($title,$arrJS=false,$arrCSS=false)
    {
        $this->arrHeaderData=array
        (
            "title"=>$title,
            "js_include"=>$arrJS,
            "css_include"=>$arrCSS
        );
    }
    public function getHeaderData()
    {
        return $this->arrHeaderData;
    }
    public function getModule()
    {
        return $this->module;
    }
    public function getAction()
    {
        return $this->action;
    }
    public function getSwitch()
    {
        return $this->switch;
    }
    public function setModule($module)
    {
        $this->module=$module;
    }
    public function setAction($action)
    {
        $this->action=$action;
    }
    public function modifyAction($action)
    {
        $this->action=$action;
    }
    public function setSwitch($switch)
    {
        $this->switch=$switch;
    }
    public function modifyModule($module)
    {
        $this->module=$module;
    }
    public function modifySwitch($switch)
    {
        $this->switch=$switch;
    }
    public function getModifiedAction()
    {
        return $this->action;
    }
    public function addSubTemplate($name,$module,$action,$switch,$arrTplVar=array(),$tpl=false)
    {
        $this->arrSubTemplate[$name]=array("module"=>$module,"action"=>$action, "switch"=>$switch, "arrTplVar"=>$arrTplVar, "tpl"=>$tpl);
    }
    public function getSubTemplate()
    {
        return $this->arrSubTemplate;
    }
    public function setGlobalTplVar($key,$data)
    {
        $this->arrTplVar[$key]=$data;
    }
    public function getGlobalTplVar()
    {
        return $this->arrTplVar;
    }
    public function getGlobalTemplateVar()
    {
        return $this->arrTplVar;
    }
    
    public function addOrderBy()
    {
        $this->arrOrderBy[]=array("field"=>$orderBy,"isAsc"=>$isAsc);
    }
    
    public static function getInstance($module)
    {
        $class=  ClsNaanalApplication::getControllerName($module);
        ClsNaanalApplication::loadController($module);
        if(!class_exists($class)) 
        {
            self::$arrErrorStatic[]=array("error"=>"class ({$class}) does not exist");
            return false;
        }
        $objClass=new $class();
        return $objClass;
    }
    
    public function setWhere($field,$data,$condition="=",$boolean="AND")
    {
        $this->arrWhere[]=array("field"=>$field,"data"=>$data,"condition"=>$condition,"boolean"=>$boolean);
    }
        
    public function __call($name,$arg)
    { 
    }
    
    public function addAdditionalInput($var,$data)
    {
        $this->arrAdditionalInput[$var]=$data;
    }
    	
    public function &getWrapper($id=0)
    {
        $wrapper=$this->wrapper;
        if(is_null($this->objPDO)) 
        {
            $exist=false;
            return $exist;
        }
        $objWrapper= ClsWrapper::getInstance($this->module);
        $objWrapper->fldID=$this->fldID;
        $objWrapper->tableName=$this->table;
        if($id===0 && !empty($this->id))
        {

        }
        if($id>0){}
        else if(!empty($this->id)) 
        {
            $id=$this->id;
        }
        if($id>0)
        {
            $objWrapper->loadObject($id);
        }
        return $objWrapper;
    }
	
    public function getRedirect()
    {
        return $this->redirect;
    }

    public function getRestart()
    {
        return $this->restart;
    } 

    function getRedirectPage()
    {
        return $this->redirect; 
    }
    /**
     * 
     * @param type $arrWhere
     * @param type $curpage (if 0, it will list all the records else specific page)
     * @param type $isCount
     * @return type
     */
    public function getListSql($arrWhere=array(),$curpage=0)
    {
        return $this->getSqlObject($arrWhere, $curpage)->render(false);
    }
    public function getSqlObject($arrWhere=array(),$curpage=0)
    {
        $arrNaanalData=empty($this->arrNaanalData)?$this->objNaanalRequest->getAll():$this->arrNaanalData;
        $objSQL=  getNaanalLibObject("ClsNaanalSQL");
        $objSQL->addTable($this->table);
        if($curpage>0)
        {
            $itemPerPage=$this->itemperpage;
            $pagevar=ClsConfig::$PAGINATION_VAR;
            $start=($curpage-1)*$itemPerPage;
            $objSQL->setLimit($start, $itemPerPage);
        }
        
        if($arrWhere)
        foreach($arrWhere as $arr)
        {
            $objSQL->addWhereAsArray($arr);
        }

        if(isset($arrNaanalData["switch"]))
        {
            switch($arrNaanalData["switch"])
            {
                case "keyword":
                {
                    $keywordParam=ClsConfig::$arrKeywordParam[$arrNaanalData["keywordparam"]];
                    $searchfields=implode(",",$keywordParam["searchFields"]);
                    $objSQL->addWhere("concat({$searchfields})", $arrNaanalData["data"],"like");
                }
            }
        }
        if($this->arrOrderBy)
        {
            foreach($this->arrOrderBy as $ind=>$orderBy)
            {
                $objSQL->addOrderBy($orderBy["orderBy"],$orderBy["isAsc"]);
            }
        }
        return $objSQL;
    }
	
    public function getListCountSql($arrWhere=array(),$curpage=0)
    {
        return $this->getSqlObject($arrWhere, $curpage)->render(true);
        /*$arrNaanalData=empty($this->arrNaanalData)?$this->objNaanalRequest->getAll():$this->arrNaanalData;
        $objSQL=new ClsSQL();
        $objSQL->addTable($this->table);

        if(isset($arrNaanalData["switch"]))
        {
            switch($arrNaanalData["switch"])
            {
                case "keyword":
                {
                    $keywordParam=ClsConfig::$arrKeywordParam[$arrNaanalData["keywordparam"]];
                    $searchfields=implode(",",$keywordParam["searchFields"]);
                    $objSQL->addWhere("concat({$searchfields})", $arrNaanalData["data"],"like");
                }
            }
        }
        return $objSQL->render(true);*/
    }

    function showList($arrWhere=array(),$arrAdditionalField=array(),$arrWrapperParam=array(),$arrRequestParam=array())
    {
        if(is_string($arrAdditionalField)) trace("List of fields(second parameter) must be in array (or) empty array, where string ($arrAdditionalField) is assigned");
        if(empty($arrWhere)) $arrWhere=$this->arrWhere;//trace($arrWhere);
        if(is_null($this->objPDO)) return false;
        $this->mode="list";
        $arrNaanalData=empty($this->arrNaanalData)?$this->objNaanalRequest->getAll():$this->arrNaanalData;
            
        $pagevar=ClsConfig::$PAGINATION_VAR;
        $curpage=isset($arrNaanalData[$pagevar])?$arrNaanalData[$pagevar]:1;
        
        $objSql= $this->getSqlObject($arrWhere);//"select count(*) from {$this->table}".$where;
        $countSql=$objSql->render(true);
        $this->objPDO->setQuery($countSql);
        $arrAssoc=$this->objPDO->getAllRow();//trace($arrAssoc);
        $totalItems=$arrAssoc[0][0];
        $paginationURL="index.php?page={$this->module}&action=list";
        foreach($arrRequestParam as $requestField=>$requestData)
        {
            $paginationURL=$paginationURL."&{$requestField}={$requestData}";
        }
        $pagination=getPagination($paginationURL,$totalItems,$curpage,$this->itemperpage);
        
        ///limiting the records to curpage records
        $objSql= $this->getSqlObject($arrWhere,$curpage);
        if(!empty($arrAdditionalField))
        {
            //$additionalSql="";
            foreach($arrAdditionalField as $ind=>$addfield)
            {
                $objSql->addField($addfield);
                /*if(empty($additionalSql))
                {
                    $additionalSql="'{$addfield}' as naanal_af{$ind}";
                }
                else
                {
                    $additionalSql=$additionalSql.", '{$addfield}' as naanal_af{$ind}";
                }*/
            }
            //$sql="select *,{$additionalSql} from {$this->table}".$where."{$orderby} limit {$start},{$itemPerPage}";
        }
        else
        {
            //$sql="select * from {$this->table}".$where."{$orderby} limit {$start},{$itemPerPage}";
        }
        $objSql->addOrderBy("id",false);
        $sql=$objSql->render();
        $success=$this->objPDO->setQuery($sql);
        if(!$success)
        {
            trace($this->objPDO->getError());
        }
        //$arrObj=$this->objPDO->getAllObject($this->wrapper,$arrWrapperParam);
        $arrObj=$this->objPDO->getAllAssoc();
        return array("list"=>$arrObj,"pagination"=>$pagination);
           // }	
    }
    function showPreview()
    {
        if(is_null($this->objPDO)) $this->objPDO=ClsNaanalPDO::getNamedInstance($this->controlpanel);
            $this->mode="preview";
            if(is_null($this->id))
            {
                    return null;
            }
            else
            {
                    $sql="select * from `".$this->table."` where id='{$this->id}'";
                    $this->objPDO->setQuery($sql);
                    $arrObj=$this->objPDO->getAllObject($this->wrapper);
                    return array("form"=>$arrObj[0]);
            }
    }
    function isDeletable()
    {

    }
    function deleteRecord()
    {
        $arrNaanalData=empty($this->arrNaanalData)?$this->objNaanalRequest->getAll():$this->arrNaanalData;
        $objWrapper=$this->getWrapper($this->arrNaanalData["id"]);
        $objWrapper->remove();
        $pagevar=ClsConfig::$PAGINATION_VAR;
        $curpage=isset($arrNaanalData[$pagevar])?$arrNaanalData[$pagevar]:1;
        $this->redirect="page={$this->module}&action=list&{$pagevar}={$curpage}";
    }
    public function createRecord()
    {
        $this->mode='create';
        return array('form'=>$this->form,'issubmit'=>false);
    }

    function editRecord()
    {
        $arrNaanalData=empty($this->arrNaanalData)?$this->objNaanalRequest->getAll():$this->arrNaanalData;
        $wrapper=$this->wrapper;
        $this->form->loadRecord($arrNaanalData['id']);
        return array('form'=>$this->form);
    }
    
    function updateRecord()
    {
        $arrNaanalData=empty($this->arrNaanalData)?$this->objNaanalRequest->getAll():$this->arrNaanalData;
        $obj=ClsWrapper::getInstance($this->module);
        $obj->setArray($arrNaanalData);
        $obj->update();
        $pagevar=ClsConfig::$PAGINATION_VAR;
        $curpage=isset($arrNaanalData[$pagevar])?$arrNaanalData[$pagevar]:1;
        $this->redirect="page={$this->module}&action=list&{$pagevar}={$curpage}";
    }

    /*function updateRecord()
    {
        $arrNaanalData=empty($this->arrNaanalData)?$this->objNaanalRequest->getAll():$this->arrNaanalData;
        $wrapper=$this->wrapper;
        $obj=new $wrapper($this->controlpanel);
        $obj->setArray($arrNaanalData);
        $obj->update();
        $pagevar=ClsConfig::$PAGINATION_VAR;
        $curpage=isset($arrNaanalData[$pagevar])?$arrNaanalData[$pagevar]:1;
        $this->redirect="page={$this->module}&action=list&{$pagevar}={$curpage}";
    }
    
    function insert()
    {
        $arrNaanalData=empty($this->arrNaanalData)?$this->objNaanalRequest->getAll():$this->arrNaanalData;
        $wrapper=$this->wrapper;
        $obj=new $wrapper($this->controlpanel);
        $obj->setArray($arrNaanalData);
        $obj->update();
        $pagevar=ClsConfig::$PAGINATION_VAR;
        $curpage=isset($arrNaanalData[$pagevar])?$arrNaanalData[$pagevar]:1;
        $this->redirect="page={$this->module}&action=list&{$pagevar}={$curpage}";
    }*/

    function insertRecord()
    {
        $arrNaanalData=empty($this->arrNaanalData)?$this->objNaanalRequest->getAll():$this->arrNaanalData;
        $wrapper=$this->wrapper;
        $obj=new $wrapper($this->module);
        $obj->setArray($arrNaanalData);
        $obj->update();
        $pagevar=ClsConfig::$PAGINATION_VAR;
        $curpage=isset($arrNaanalData[$pagevar])?$arrNaanalData[$pagevar]:1;
        $this->redirect="page={$this->module}&action=list&{$pagevar}={$curpage}";
    }
}